package com.jh.user.controller;

import cn.jh.common.exception.ServiceException;
import cn.jh.common.utils.CommonsUtil;
import com.jh.user.business.ShopRegisterBussiness;
import com.jh.user.business.ThirdPayRateBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.controller.model.RangeRateModel;
import com.jh.user.controller.model.ThirdPayRateRequest;
import com.jh.user.controller.model.ThirdPayRateVO;
import com.jh.user.pojo.*;
import com.jh.user.pojo.enums.ThirdPayType;
import com.jh.user.repository.UserAccountRepository;
import com.jh.user.service.PlatformService;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static io.jsonwebtoken.lang.Strings.hasText;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.jh.common.utils.BaseApi.JSON_UTF8;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * @author Yichuan
 * @version 1.0
 */
@RestController
public class ThirdPayRateController {

    private final ThirdPayRateBusiness thirdPayRateBusiness;
    private final PlatformService platformService;
    private final UserLoginRegisterBusiness userLoginRegisterBusiness;
    private final UserAccountRepository userAccountRepository;
    private final ShopRegisterBussiness shopRegisterBussiness;

    @Autowired
    public ThirdPayRateController(ThirdPayRateBusiness thirdPayRateBusiness,
                                  UserLoginRegisterBusiness userLoginRegisterBusiness,
                                  PlatformService platformService,
                                  UserAccountRepository userAccountRepository,
                                  ShopRegisterBussiness shopRegisterBussiness) {
        this.thirdPayRateBusiness = thirdPayRateBusiness;
        this.userLoginRegisterBusiness = userLoginRegisterBusiness;
        this.platformService = platformService;
        this.userAccountRepository = userAccountRepository;
        this.shopRegisterBussiness = shopRegisterBussiness;
    }

    /**
     * 查询公共第三方支付费率信息
     */
    @RequestMapping(method = POST, value = "/v1.0/user/third_pay/rate/query", produces = JSON_UTF8)
    public Object findThirdPayRate(@RequestParam("brandId") Long brandId) {
        List<ThirdPayRate> result = thirdPayRateBusiness.findThirdPayRate(brandId);
        return CommonsUtil.returnOK(ThirdPayRateVO.transform(result));
    }

    /**
     * 更新公共第三方支付费率
     */
    @RequestMapping(method = POST, value = "/v1.0/user/third_pay/rate/update", produces = JSON_UTF8)
    public Object updateThirdPayRate(@RequestBody ThirdPayRateRequest thirdRequest) {
        try {
            thirdRequest.validation();

            ThirdPayRate thirdPayRate = thirdPayRateBusiness.updateThirdPayRate(thirdRequest);
            if (thirdPayRate == null) {
                return CommonsUtil.returnError("费率更新失败");
            }
            return CommonsUtil.returnOK(ThirdPayRateVO.transform(thirdPayRate));
        } catch (ServiceException ex) {
            return CommonsUtil.returnError(ex.getMessage());
        }
    }

    /**
     * 返回统计所需的第三方费率信息
     */
    @RequestMapping(method = POST, value = "/v1.0/user/third_pay/rate/brand", produces = JSON_UTF8)
    public Map<ThirdPayType, List<RangeRateModel>> findBrandPayRate(
            @RequestParam(value = "brandId", required = false, defaultValue = "407") Long brandId) {
        List<ThirdPayRate> result = thirdPayRateBusiness.findThirdPayRate(brandId);
        return result.stream().collect(Collectors.toMap(ThirdPayRate::getType, ThirdPayRate::getRangeList));
    }

    /**
     * 查询公共第三方支付费率信息
     */
    @RequestMapping(method = POST, value = "/v1.0/user/third_pay/rate", produces = JSON_UTF8)
    public Object findByThirdPayRate(@RequestParam(value = "brandId", required = false, defaultValue = "407") Long brandId,
                                     @RequestParam(value = "amount") BigDecimal amount,
                                     @RequestParam(value = "userId", required = false, defaultValue = "0") Long userId,
                                     @RequestParam(value = "payType") String payType,
                                     @RequestParam(value = "platformCode", required = false) String  platformCode) {
        Map<String,Object> pram = new HashMap<>();
        Platform platform = new Platform();
        if (userId < 1) {
            if (!hasText(platformCode)) {
                return CommonsUtil.returnError("用户id不能为空");
            }
            platform = platformService.findPlatform(platformCode, "2");
            if (platform == null) {
                return CommonsUtil.returnError("该台卡不可用");
            }
            String mo = platform.getShopId();
            User user = userLoginRegisterBusiness.queryUserByPhone(mo);
            if (user == null) {
                return CommonsUtil.returnError("没有该商户信息");
            }
            userId = user.getId();
        }
        ThirdPayRate result = thirdPayRateBusiness.findByBrandIdAndThirdPayType(brandId,ThirdPayType.of(payType));
        Map<Object,Object> rate = result.getPayRateMap(amount);
        User user = userLoginRegisterBusiness.queryUserById(userId);
        User users = userLoginRegisterBusiness.queryUserByPhone(platform.getAgent());
        ShopRegister shopRegister = shopRegisterBussiness.findByUserId(user.getId());
//        if (hasText(platform.getAgent())) {
//            //UserAccount account = userAccountRepository.getUserAccount(users.getId());
//            //BigDecimal rebateBalance =  account.getRebateBalance();
//            //BigDecimal sumRebateBalance = account.getSumRebateBalance();
//            double agentRate = MapUtils.getDouble(rate,"agentRate");
//            BigDecimal agent = amount.multiply(new BigDecimal(agentRate));
//            rebateBalance = rebateBalance.add(agent);
//            sumRebateBalance = sumRebateBalance.add(agent);
//            //account.setRebateBalance(rebateBalance.setScale(2,BigDecimal.ROUND_UP));
//            //account.setSumRebateBalance(sumRebateBalance.setScale(2,BigDecimal.ROUND_UP));
//            //userAccountRepository.save(account);
//        }

        pram.put("user",user);
        pram.put("model",rate);
        pram.put("agentId",users.getId());
        pram.put("shopRegister",shopRegister);
        return CommonsUtil.returnOK(pram);
    }
}
